package com.choosefine.it.usercent;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.choosefine.it.base.BaseController;
import com.choosefine.it.common.def.ResultCode;
import com.choosefine.it.common.json.JsonResult;
import com.choosefine.it.common.model.CustomRestTemplate;
import com.choosefine.it.common.utils.URLHandlerUtils;
import com.choosefine.it.usercent.vo.UserLoginVO;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 用户登陆
 * 
 * @author chenjian
 * @date 2016-11-23 下午1:44:48
 */
@RestController
@RequestMapping("/userLogin")
@Api(value = "用户登陆", description = "陈健")
public class UserCenterController extends BaseController{

	@Autowired
	ObjectMapper jsonObjectMapper;
	@Autowired
	CustomRestTemplate restTemplate;
	private Logger logger = LoggerFactory.getLogger(UserCenterController.class);

	@Value("#{yaml.get('shixiaobao.privilege.login')}")
	String userloginURL = null;

	@Value("#{yaml.get('shixiaobao.privilege.changePwd')}")
	String userchangePwdURL = null;

	@Value("#{yaml.get('shixiaobao.privilege.logout')}")
	String userlogoutURL = null;

	/**
	 * 用户登录
	 * 
	 * @author chenjian
	 * @param userName 用户名
	 * @param password 密码
	 * @return inputLine
	 * @throws IOException
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/login")
	@ApiOperation(value = "用户登陆", notes = "测试用户帐号：android，IOS，web各5个帐号，例android1，IOS5，web3；密码：123456", response = UserLoginVO.class)
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "userName", value = "登录名", required = true, dataType = "String"),
			@ApiImplicitParam(paramType = "query", name = "password", value = "密码", required = true, dataType = "String"),
			@ApiImplicitParam(paramType = "query", name = "ip", value = "ip地址", required = true, dataType = "String"),
			@ApiImplicitParam(paramType = "query", name = "source", value = "来源（手机系统及型号）", required = true, dataType = "String") })
	public String login(
			@RequestParam(value = "userName", required = true) String userName,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "ip", required = false) String ip,
			@RequestParam(value = "source", required = true) String source)
			throws IOException {
		String result = null;
		UserLoginVO loginvo = new UserLoginVO();
		
		String url = URLHandlerUtils.getUrlBuffer(usercentURL, userloginURL).toString();
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("userName", userName);
		param.put("password", password);
		param.put("ip", ip);
		param.put("source", source);
		url = URLHandlerUtils.DefaultUriTemplateHandler(url, param);
		ParameterizedTypeReference<JsonResult<UserLoginVO>> parameterizedTypeReference = new ParameterizedTypeReference<JsonResult<UserLoginVO>>() {
		};
		ResponseEntity<JsonResult<UserLoginVO>> exchange = restTemplate.exchange(url, HttpMethod.GET, null, parameterizedTypeReference, "");
		JsonResult<UserLoginVO> returnMsg = exchange.getBody();
		loginvo = returnMsg.getData();
		if (loginvo != null) {
			result = responseSuccess(loginvo);
			logger.info("用户登陆responseEntity.getBody().toString()\n"
					+ loginvo.toString());
		} else {
			result = responseFail(ResultCode.MSG_LOGIN_FAILD);
		}
		return result;
	}

	/**
	 * 用户登出
	 * 
	 * @author chenjian
	 * @param userName
	 *            用户名
	 * @param token
	 * @throws IOException
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/logout")
	@ApiOperation(value = "用户登出", notes = "测试用户帐号")
	@ApiImplicitParams({ @ApiImplicitParam(paramType = "query", name = "userName", value = "登录名", required = true, dataType = "String") })
	public String logout(
			@RequestParam(value = "userName", required = true) String userName)
			throws IOException {
		String url = null;
		Map<String, Object> param = new HashMap<String, Object>();
		
		param.put("userName", userName);
		url = URLHandlerUtils.DefaultUriTemplateHandler(URLHandlerUtils.getUrlBuffer(shixiaobaoURL,  userlogoutURL).toString(), param);
		ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
		String resultString = responseEntity.getBody().toString();
		logger.info("用户登出responseEntity.getBody().toString()\n" + resultString);
		return resultString;
	}

	/**
	 * 修改密码
	 * 
	 * @param userName
	 *            用户名
	 * @param oldPassword
	 *            原始密码
	 * @param newPassword
	 *            新密码
	 * @author chenjian
	 */
	@RequestMapping(method = RequestMethod.PUT, value = "/changePwd")
	@ApiOperation(value = "用户修改密码", notes = "测试用户帐号")
	public String changePwd(
			@RequestParam(value = "phone", required = true) String phone,
			@RequestParam(value = "oldPassword", required = true) String oldPassword,
			@RequestParam(value = "newPassword", required = true) String newPassword) throws IOException {
		String url = null;
		Map<String, Object> param = new HashMap<String, Object>();

		param.put("phone", phone);
		param.put("oldPassword", oldPassword);
		param.put("newPassword", newPassword);
		url = URLHandlerUtils.DefaultUriTemplateHandler(URLHandlerUtils.getUrlBuffer(shixiaobaoURL,  userchangePwdURL).toString(), param);
		ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, null, String.class);
		String resultString = responseEntity.getBody().toString();
		logger.info("用户修改密码responseEntity.getBody().toString()\n"
				+ resultString);
		param = null;
		return resultString;
	}

}
